<?php
/**
 * Created by PhpStorm.
 * User: ly
 * Date: 2018\1\8 0008
 * Time: 10:22
 */

namespace backend\controllers;

use backend\controllers\BaseController;
use common\models\InstationMessage;
use backend\models\User;
use common\models\ApplicationResult;
use common\models\Country;
use common\models\Package;
use common\models\PackageApplication;
use common\models\Project;
use common\models\UserModel;
use PHPUnit\Runner\Exception;
use yii\data\Pagination;
use yii;
use common\models\Responses;
use yii\widgets\LinkPager;
use yii\data\Sort;

class AuditManagementController extends BaseController
{

//    public $freeAccessActions = [];
    const PAGE_NUM = 10;

    public function behaviors()
    {
        return [
            'ghost-access' => [
                'class' => GhostAccessControl::className(),
            ],
        ];
    }

    /*
     * 立项审批（ly）
     * */
    public function actionIndex()
    {
        /*application_result */
        /*审批状态: 不限（为空） 未审批（1） 已审批（大于1）
         * result
         *审批结果 不限（为空）  通过（2）   未通过（3）
         * */
        //---添加项目审核专员添加--fly-start----
        //审核员角色
        $myUser = Yii::$app->user->getId();
        $user_id = array_column(json_decode(User::getRolesUser('Projectapprovalspecialist'), true)['data']['res'], 'user_id');
        if (!empty($user_id)) {
            if (in_array($myUser, $user_id)) {
                //---添加项目审核专员添加--fly-end----
                $data = PackageApplication::find()->from(PackageApplication::tableName() . ' as PA')//CC.title as cityName
                ->select('P.code,P.title,P.principal,C.title as provinceName,P.city,U.realname,PA.reason,PA.applied_at,AR.result,AR.note,AR.application_id,AR.id,PA.package_id')
                    ->leftJoin(ApplicationResult::tableName() . ' as AR', 'AR.application_id=PA.id')
                    ->leftJoin(Package::tableName() . ' as P', 'P.id=PA.package_id')
                    ->leftJoin(User::tableName() . ' as U', 'U.id=PA.proposer')
                    ->leftJoin(Country::tableName() . ' as C', 'C.id=P.province')
//            ->leftJoin(Country::tableName() . ' as CC', 'CC.id=P.city')
                    ->where('PA.type=1');
                if (Yii::$app->request->isGet && (Yii::$app->request->get('keyWords') != '' || Yii::$app->request->get('result') != '')) {
                    $keyWords = Yii::$app->request->get('keyWords');
                    $result = Yii::$app->request->get('result');

                    if ($result == 4) { //不等于1 及已经审核的
                        $data->andWhere('AR.result<>1');
                    } else {
                        $data->andFilterWhere(['AR.result' => intval($result)]);
                    }
                    if (!empty($keyWords)) {
                        $data->andWhere("P.title like :keyWords  or U.realname like :keyWords", [
                            ':keyWords' => '%' . $keyWords . '%'
                        ]);
                    }
                }
                //$data = PackageApplication::find()->with('result', 'package.provinceName', 'package.cityName', 'user')->where('type=1');
                /*查询 立项审批申请*/
                //-------------修改消息状态--变为已读----fly---------------------
                $messageState = Yii::$app->request->get('message_state', 1);
                $userId = Yii::$app->request->get('sender', 1);
                $user_id = \Yii::$app->user->getId();
                $messageType = Yii::$app->request->get('message_group', 0);;
                if ($messageState == 2 && $userId == $user_id && $messageType == 12) {
                    $param['message_user_group_id'] = Yii::$app->request->get('message_user_group_id', 1);

                    $instationMessageState = InstationMessage::readAdminMessage($param);
                    if ($instationMessageState['code'] == 400) {
                        return false;
                    }
                }
                //-------------修改消息状态--变为已读----fly---------------------
                $data->orderBy(['PA.workflow_status' => SORT_ASC, 'PA.applied_at' => SORT_DESC]);
                $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => 10]);    //$pageSize实例化分页类,带上参数(总条数,每页显示条数)
                $data_array = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
                //------------- 通过点击本页面按钮，不跳转----fly---------------------
                $dianji = Yii::$app->request->get('dianji', 2);
                if ($dianji == 1) {
                    return $this->renderPartial('myApproval', ['data' => $data_array, 'pages' => $pages, 'type' => Yii::$app->params['LIXIANG']]);
                }
                //-------------通过点击本页面按钮，不跳转----fly---------------------
                return $this->render('index', ['data' => $data_array, 'pages' => $pages, 'type' => Yii::$app->params['LIXIANG'], 'is_show' => 1]);
            }
            //不是审核专员
            return $this->render('index', ['data' => [], 'pages' => [], 'type' => Yii::$app->params['LIXIANG'], 'is_show' => 0]);
        } else {
            //无审核转员
            return $this->render('index', ['data' => [], 'pages' => [], 'type' => Yii::$app->params['LIXIANG'], 'is_show' => 0]);
        }
    }

    /*
     * 提交立项审核情况
     * */
    public function actionAuditForm()
    {

        if (Yii::$app->request->isPost) {
            $note = Yii::$app->request->post('note');
            $is_package = Yii::$app->request->post('is_package');  //fly
            $result = Yii::$app->request->post('result');
            $application_id = Yii::$app->request->post('application_id');
            $result_id = Yii::$app->request->post('result_id');
            if (empty($note)) return json_encode(Responses::response404('立项审核-审批意见不能为空'));
            if ($result == 1) {//保存草稿
                $res = ApplicationResult::findOne($result_id);
                $attributes['application_id'] = $application_id;
                $attributes['result'] = $result;
                $attributes['note'] = $note;
                $attributes['is_package'] = $is_package;  //fly
                $res->setAttributes($attributes);
                if ($res->save()) {
                    return json_encode(Responses::response200('', 1, '立项审批-保存草稿成功'));
                }
                return json_encode(Responses::response404('立项审批-保存草稿失败'));
            } elseif ($result == 2 || $result == 3) {//提交立项审核
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    /*提交审核结果*/
                    $res = ApplicationResult::findOne($result_id);
                    $res->application_id = $application_id;
                    $res->result = $result;
                    $res->note = $note;
                    $res->user_id = Yii::$app->user->getId();//审批人id

                    if (!$res->save()) throw new \Exception('提交审核结果失败');

                    /*资产包申请立项 状态更改*/
                    $res = PackageApplication::findOne($application_id);
                    $package_id = $res['package_id'];

                    $res->setAttributes(['workflow_status' => 2]);
                    if (!$res->save()) throw new \Exception('申请立项状态更新失败');
                    if ($result == 2) {//package_id z资产包立项成功 生成编码及项目 已立项 province_code
                        $province_code = Yii::$app->params['province_code'];
                        $res = Package::findOne($package_id);
                        //D17OO-SX15 OO
                        //-----fly 2018-03-04 07:39--- 如果 没有填写城市则提示
                        if (!empty($res->province)) {
                            $package_code = 'D' . date('y') . 'OO-' . $province_code[$res->province];//'title', 'type', 'owner'
                        } else {
                            $transaction->rollBack();
                            return json_encode(Responses::response404('没有添加城市信息'));//'立项审核-提交审批失败！'
                        }
                        $num = Package::find()->where(['like', 'code', $package_code . "%", false])->count();
                        $num++;
                        $num = str_pad($num, 2, '0', STR_PAD_LEFT);
                        $package_code .= $num;
                        $package_data['code'] = $package_code;
                        $package_data['state'] = 4;
                        $res = Yii::$app->db->createCommand()->update(Package::tableName(), $package_data, "id=$package_id")->execute();
                        if (!$res) throw new \Exception('资产包状态更新失败');
                        $res = Project::findAll(['package_id' => $package_id]);
                        $i = 0;
                        foreach ($res as $val) {
                            $i++;
                            $num = str_pad($i, 4, '0', STR_PAD_LEFT);
                            $project_data['code'] = $package_code . '-' . $num;
                            $project_data['status'] = 4;
                            $res2 = Yii::$app->db->createCommand()->update(Project::tableName(), $project_data, "id=:id", [':id' => $val['id']])->execute();
                            if (!$res2) throw new \Exception('项目状态更新失败');
                        }
                    } else {//立项待跟进 更新资产包和项目的状态
                        // $res = Package::findOne($package_id);
                        $package_data['state'] = 5;
                        $res = Yii::$app->db->createCommand()->update(Package::tableName(), $package_data, "id=$package_id")->execute();
                        if (!$res) throw new \Exception('资产包状态更新失败');
                        $res = Project::findAll(['package_id' => $package_id]);
                        foreach ($res as $val) {
                            $project_data['status'] = 5;
                            $res2 = Yii::$app->db->createCommand()->update(Project::tableName(), $project_data, "id=:id", [':id' => $val['id']])->execute();
                            if (!$res2) throw new \Exception('项目状态更新失败');
                        }
                    }

                    //-------------------审核立项-发送消息----(fly)-----------
                    $pack_name = (new \yii\db\Query())->from(Package::tableName())->where(['=', 'id', $package_id])->one()['title'];
                    $application = "立项审批"; //"立项审批";
                    $appStatus = $result == 2 ? 1 : 2;  //审批状态 1 表示审核成功 2表示审核失败
                    $approver = \Yii::$app->user->getId(); //审批人
                    $applicant_name = (new \yii\db\Query())->from(User::tableName())->where(['=', 'id', $approver])->one()['realname'];
                    $applicant_bumen = (new \yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai', 'user.department = ai.name')->where(['=', 'id', $approver])->one()['description'];
                    $appSuggest = $note;//审批意见
                    $messageArr = [
                        'pack_name' => $pack_name,
                        'application' => $application,
                        'appStatus' => $appStatus,
                        'approver' => $applicant_bumen . '-' . $applicant_name,
                        'appSuggest' => $appSuggest,
                    ];
                    $appModel = PackageApplication::findOne($application_id);
                    if (!empty($appModel)) {
                        $user_id = [$appModel->proposer];
                    } else {
                        $user_id = 0;
                    }
                    //如果没有审核管理员则不发送数据
                    if (!empty($user_id) && is_array($user_id)) {
                        $data = [];
                        $data['sender'] = \Yii::$app->user->getId();//发件人id
                        $data['package_project_id'] = $package_id;//资产包id
                        $data['is_package'] = 1;//是否是资产包/1是资产包/2是项目
                        $data['message_val'] = json_encode($messageArr); //消息内容 json

                        $data['user_id'] = $user_id;//收件人id
                        $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
                        //区分是发送消息是 立项/审批
                        $is_fangwen = Yii::$app->request->post('is_fangwen', 1); //1立项 2访问
                        if ($is_fangwen) {
                            $data['message_group'] = \Yii::$app->params['SHENPIN_FANKUI_LX']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/
                        } else {
                            $data['message_group'] = \Yii::$app->params['SHENPIN_FANKUI_FW']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/
                        }

                        $param = [];
                        $param['where_sender'] = \Yii::$app->user->getId();//发件人id
                        $param['where_is_package'] = 1;//是否是资产包/1是资产包/2是项目
                        $param['where_package_project_id'] = $package_id;//资产包id
                        if ($is_fangwen) {
                            $param['where_message_group'] = \Yii::$app->params['SHENPIN_FANKUI_LX'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                        } else {
                            $param['where_message_group'] = \Yii::$app->params['SHENPIN_FANKUI_FW'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                        }
                        $messageState = InstationMessage::saveMessage($param, $data);
                    } else {
                        $messageState['code'] = 200;
                        $messageState['message'] = '审批成功,无审核管理员,没发送消息';
                    }
                    if (!empty($messageState) && $messageState['code'] == 200) {
                        $transaction->commit();
                        return json_encode(Responses::response200('', 1, '审批成功-发送消息成功'));
                    } else {
                        $transaction->rollBack();
                        return json_encode(Responses::response400('审批成功-发送消息失败'));
                    }
                    //-------------------审核立项-----发送消息------(fly)------
                } catch (\Exception $e) {
                    $transaction->rollBack();
//                    $this->_lastError=$e->getMessage();
                    return json_encode(Responses::response404($e->getMessage()));//'立项审核-提交审批失败！'
                }
            }
        }
        return json_encode(Responses::response404('立项审核情况有误！'));
    }


    /*
     * 访问审批展示
     */
    public function actionAccess()
    {
        $type = Yii::$app->params['FANGWEN'];
        $result = Yii::$app->request->get('result', 0);
        $resultD = Yii::$app->request->get('resultD', 1);
        $accessKey = Yii::$app->request->get('accessKey', '');
        //-------------修改消息状态--变为已读----fly---------------------
        $messageState = Yii::$app->request->get('message_state', 1);
        //查看审批人的数据
        $user_id = \Yii::$app->user->getId();
        $userIdData = (new \yii\db\Query())->select('application_id')->from('application_result')->where(['=', 'user_id', $user_id])->all();
        $paramAccess['message_user_group_id'] = Yii::$app->request->get('message_user_group_id', 1);
        $messageType = Yii::$app->request->get('message_group', 0);
        //判断状态 是否为管理员  是否已经改变状态
        if ($messageState == 2 && !empty($userIdData) && $messageType == 11) {
            $instationMessageState = InstationMessage::readAdminMessage($paramAccess);
            if ($instationMessageState['code'] == 400) {
                return false;
            }
        }
        //-------------修改消息状态--变为已读----fly---------------------
        if (empty($accessKey)) {
            $whereAccessKey = [];
        } else {
            $whereAccessKey = ['or', ['like', 'pac.title', $accessKey], ['like', 'pro.title', $accessKey], ['like', 'u.realname', $accessKey]];
        }
//            $whereResult =
        //1未审核，2通过，3未通过 4已审核
        switch ($result) {
            case 1:
                $whereResult = ['=', 'result', $result];
                break;
            case 4:
                $whereResult = ['!=', 'result', 1];
                break;
            default:
                $whereResult = [];
                break;
        }
        //1未审核，2通过，3未通过 4已审核
        if ($result != 1) {
            switch ($resultD) {
                case 2:
                    $whereResult = ['=', 'result', $resultD];
                    break;
                case 3:
                    $whereResult = ['=', 'result', $resultD];
                    break;
                default:
                    if ($result == 4) {
                        $whereResult = ['or', ['=', 'result', 2], ['=', 'result', 3]];
                    } else {
                        $whereResult = [];
                    }
                    break;
            }
        } else {
            $whereResult = ['=', 'result', 1];
        }
        $userId = Yii::$app->user->getId();
        //---------------未审批的通过/未通过-个数----fly--start------
        $wShenHeNum = $data = (new \yii\db\Query())->select('*,ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('user as u', 'pa.proposer = u.id')
            ->leftJoin('package as pac', 'pa.package_id = pac.id')
            ->leftJoin('project as pro', 'pa.package_id = pro.id')
            ->where(['=', 'pa.type', $type])
            ->andWhere(['=', 'ar.user_id', $userId])
            ->andWhere($whereAccessKey)
            ->andWhere(['=', 'result', 1])->count();
        //---------------未审批的通过/未通过-个数-fly-------end-------
        //---------------审批的通过/未通过----个数--fly- start---------
        $ShenHeTGNum = $data = (new \yii\db\Query())->select('*,ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('user as u', 'pa.proposer = u.id')
            ->leftJoin('package as pac', 'pa.package_id = pac.id')
            ->leftJoin('project as pro', 'pa.package_id = pro.id')
            ->where(['=', 'pa.type', $type])
            ->andWhere(['=', 'ar.user_id', $userId])
            ->andWhere($whereAccessKey)
            ->andWhere(['=', 'result', 2])->count();
        $ShenHeWTGNum = $data = (new \yii\db\Query())->select('*,ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('user as u', 'pa.proposer = u.id')
            ->leftJoin('package as pac', 'pa.package_id = pac.id')
            ->leftJoin('project as pro', 'pa.package_id = pro.id')
            ->where(['=', 'pa.type', $type])
            ->andWhere(['=', 'ar.user_id', $userId])
            ->andWhere($whereAccessKey)
            ->andWhere(['=', 'result', 3])->count();
        //---------------审批的通过/未通过----个数--fly-------end---
        $userId = Yii::$app->user->getId();
        $data = (new \yii\db\Query())->select('* ,pac.province as package_province , pac.city as package_city ,  pac.title as package_title , pac.id as package_id , pro.id as project_id, ar.id as result_id')->from('package_application as pa')
            ->leftJoin('application_result as ar', 'pa.id = ar.application_id')
            ->leftJoin('user as u', 'pa.proposer = u.id')
            ->leftJoin('package as pac', 'pa.package_id = pac.id')
            ->leftJoin('project as pro', 'pa.package_id = pro.id')
            ->where(['=', 'pa.type', $type])
            ->andWhere($whereAccessKey)
            ->andWhere(['=', 'ar.user_id', $userId])
            ->andWhere($whereResult);
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => self::PAGE_NUM]);
        $data = $data->offset($pages->offset)->limit($pages->limit)->orderBy(['pa.workflow_status' => SORT_ASC, 'pa.applied_at' => SORT_DESC])->all();
        //---添加项目审核专员添加--fly-start----
        //审核员角色
        $myUser = Yii::$app->user->getId();
        $user_id = array_column(json_decode(User::getRolesUser('Projectapprovalspecialist'), true)['data']['res'], 'user_id');
        if (!empty($user_id)) {
            if (in_array($myUser, $user_id)) {
                //---添加项目审核专员添加--fly-end----
                if (Yii::$app->request->isAjax) {
                    return $this->renderPartial('myAccess', [
                        'data' => $data,
                        'pages' => $pages,
                        'type' => $type,
                        'ShenHeTGNum' => $ShenHeTGNum,
                        'ShenHeWTGNum' => $ShenHeWTGNum,
                        'wShenHeNum' => $wShenHeNum,
                        'is_show' => 1
                    ]);
                } else {
                    return $this->render('index', ['data' => $data, 'pages' => $pages, 'type' => $type,
                        'ShenHeTGNum' => $ShenHeTGNum,
                        'ShenHeWTGNum' => $ShenHeWTGNum,
                        'wShenHeNum' => $wShenHeNum, 'is_show' => 1
                    ]);
                }
            } else {
                if (Yii::$app->request->isAjax) {
                    return $this->renderPartial('myAccess', [
                        'data' => $data,
                        'pages' => $pages,
                        'type' => $type,
                        'ShenHeTGNum' => $ShenHeTGNum,
                        'ShenHeWTGNum' => $ShenHeWTGNum,
                        'wShenHeNum' => $wShenHeNum,
                        'is_show' => 0
                    ]);
                } else {
                    return $this->render('index', ['data' => $data, 'pages' => $pages, 'type' => $type,
                        'ShenHeTGNum' => $ShenHeTGNum,
                        'ShenHeWTGNum' => $ShenHeWTGNum,
                        'wShenHeNum' => $wShenHeNum, 'is_show' => 0
                    ]);
                }
            }
        }
    }


    /**
     * 我发起的审批
     * @return string
     */
    public function actionMyApplication()
    {
        $userId = Yii::$app->user->id;
        $usermodel = UserModel::findOne($userId);
        $realname = $usermodel->realname;

        $page = 1; //当前页
        $pageSize = 10; //默认每页显示条数

        //列表数据
        $model = new PackageApplication();
        $offset = ($page - 1) * $pageSize;
        $limit = " limit {$offset},{$pageSize} ";
        $data = $model->getList(" WHERE application.proposer={$userId} ", '', ' ORDER BY  application.id DESC', $limit);

        //分页
        $allCounts = $model->getCounts(" WHERE application.proposer={$userId} ");//所有条数
        $pages = new Pagination(['pageSize' => $pageSize, 'totalCount' => $allCounts[0]]);
        $linkpager = LinkPager::widget([
            'pagination' => $pages,
            'hideOnSinglePage' => false,
            'maxButtonCount' => 10, //默认显示10页
            'nextPageLabel' => '下一页',
            'prevPageLabel' => '上一页',
            'firstPageLabel' => '首页',
            'lastPageLabel' => '尾页',
            //'options' => ['class' => 'm-pagination'],
        ]);

        //总数——审批结果
        $approvalCounts = $model->getCounts(" WHERE application.type=1 ");//立项审批条数
        $visitCounts = $model->getCounts(" WHERE application.type=5 ");//访问审批条数
        $passCounts = $model->getCounts(" WHERE application.proposer={$userId} AND application.result=2 AND application.workflow_status=2 ");//通过条数
        $refuseCounts = $model->getCounts(" WHERE application.proposer={$userId} AND application.result=3 AND application.workflow_status=2 ");//未通过条数
        $unauditedCounts = $model->getCounts(" WHERE application.proposer={$userId} AND application.result=1  AND application.workflow_status=1 ");//未审核条数
        //总数——审批进程
        //$finishesCounts = $model->getCounts(" WHERE application.proposer={$userId} AND application.workflow_status=1 ");//未审批条数
        //$finishedCounts = $model->getCounts(" WHERE application.proposer={$userId} AND application.workflow_status=2 ");//已审批条数

        $counts = array(
            'allCounts' => $allCounts[0],
            'approvalCounts' => $approvalCounts[0],
            'visitCounts' => $visitCounts[0],
            'passCounts' => $passCounts[0],
            'refuseCounts' => $refuseCounts[0],
            'unauditedCounts' => $unauditedCounts[0],
            //'finishesCounts' => $finishesCounts[0],
            //'finishedCounts' => $finishedCounts[0],
        );
        //---添加项目审核专员添加--fly-start----
        //审核员角色
        $myUser = Yii::$app->user->getId();
        $user_id = array_column(json_decode(User::getRolesUser('Projectapprovalspecialist'), true)['data']['res'], 'user_id');
        if (!empty($user_id)) {
            if (in_array($myUser, $user_id)) {
                //---添加项目审核专员添加--fly-end----
                return $this->render('my-application', ['data' => $data, 'pages' => $linkpager, 'counts' => $counts, 'pageSize' => $pageSize, 'realname' => $realname, 'is_show' => 1]);
            } else {
                return $this->render('my-application', ['data' => $data, 'pages' => $linkpager, 'counts' => $counts, 'pageSize' => $pageSize, 'realname' => $realname, 'is_show' => 0]);
            }
        } else {
            return $this->render('my-application', ['data' => $data, 'pages' => $linkpager, 'counts' => $counts, 'pageSize' => $pageSize, 'realname' => $realname, 'is_show' => 0]);
        }
    }


    /**
     * 分页
     */
    public function actionAjaxApplication()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $usermodel = UserModel::findOne($userId);
            $realname = $usermodel->realname;

            $get = Yii::$app->request->get();
            $page = (int)Yii::$app->request->get('page', 1); //当前页
            $pageSize = (int)Yii::$app->request->get('pageSize', 10); //默认每页显示条数
            $search = $get['search']; //搜索条件
            $workflow_status = $get['workflow_status']; //审批进程,  1进行中, 2完成
            $result = (int)$get['result']; //审批结果 1未审核，2通过，3未通过，
            $index = (int)Yii::$app->request->get('index', 0);

            $ajax = [
                'page' => $page,
                'pageSize' => $pageSize,
                'search' => $search,
                'workflow_status' => $workflow_status,
                'result' => $result,
                'index' => $index,
            ];

            $where = " WHERE application.proposer={$userId} ";
            $whereSearch = " WHERE application.proposer={$userId} ";
            if ($search != '') {
                $whereSearch = $where .= " AND (application.application_tilte LIKE '%{$search}%' OR application.realname LIKE '%{$search}%') ";
            }

            if ($workflow_status > 0) {
                $where .= "AND application.workflow_status={$workflow_status} ";
            }

            if ($result > 0) {
                if ($result == 99) {
                    $where .= "AND application.result>1 ";
                } else {
                    $where .= "AND application.result={$result} ";
                }
            }

            $model = new PackageApplication();
            //数据列表
            $offset = ($page - 1) * $pageSize;
            $limit = " limit {$offset},{$pageSize} ";
            $data = $model->getList($where, $group = '', $order = 'ORDER BY  application.id DESC', $limit);

            //数据分页
            $count = $model->getCounts($where);//所有条数
            $pages = new Pagination(['pageSize' => $pageSize, 'totalCount' => $count[0]]);
            $linkpager = LinkPager::widget([
                'pagination' => $pages,
                'hideOnSinglePage' => false,
                'maxButtonCount' => 10, //默认显示10页
                'nextPageLabel' => '下一页',
                'prevPageLabel' => '上一页',
                'firstPageLabel' => '首页',
                'lastPageLabel' => '尾页',
                //'options' => ['class' => 'm-pagination'],
            ]);

            //总数——审批结果
            $allCounts = $model->getCounts($whereSearch);
            //$approvalCounts = $model->getCounts(" WHERE application.type=1 ");//立项审批条数
            //$visitCounts = $model->getCounts(" WHERE application.type=5 ");//访问审批条数
            $passCounts = $model->getCounts($whereSearch . " AND application.result=2 AND application.workflow_status=2 ");//通过条数
            $refuseCounts = $model->getCounts($whereSearch . " AND application.result=3 AND application.workflow_status=2 ");//未通过条数
            $unauditedCounts = $model->getCounts($whereSearch . " AND application.result=1  AND application.workflow_status=1 ");//未审核条数
            //总数——审批进程
            //$finishesCounts = $model->getCounts($whereSearch . " AND application.workflow_status=1 ");//未审批条数
            //$finishedCounts = $model->getCounts($whereSearch . " AND application.workflow_status=2 ");//已审批条数

            $counts = array(
                'allCounts' => $allCounts[0],
                //'approvalCounts' => $approvalCounts[0],
                //'visitCounts' => $visitCounts[0],
                'passCounts' => $passCounts[0],
                'refuseCounts' => $refuseCounts[0],
                'unauditedCounts' => $unauditedCounts[0],
                //'finishesCounts' => $finishesCounts[0],
                //'finishedCounts' => $finishedCounts[0],
            );

            $str2 = $this->renderPartial('my-application-page2', ['data' => $data, 'pages' => $linkpager, 'counts' => $counts, 'pageSize' => $pageSize, 'ajax' => $ajax, 'realname' => $realname, 'count' => $count[0]]);
            $data = array(
                'str2' => $str2,
                'ajax' => $ajax
            );

            return Responses::response200($data, 1, 'success');
        }
    }

    /**
     * 审核访问
     */

    public function actionSaveFwState()
    {
        $application_id = (int)Yii::$app->request->post('application_id', 1); //
        $is_package = (int)Yii::$app->request->post('is_package', 1); //
        $result_id = (int)Yii::$app->request->post('result_id', 1); //
        $noteFW = Yii::$app->request->post('noteFW', ''); //
        $is_tg = (int)Yii::$app->request->post('is_tg', 1); //1未审核 2通过 3未通过

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $applicationResult = ApplicationResult::findOne($result_id);
            if (!empty($applicationResult)) {
                $applicationResult->result = $is_tg;
                $applicationResult->note = $noteFW;
                $applicationResultState = $applicationResult->save(false);
            }
            $packageApplication = PackageApplication::findOne($application_id);
            $package_id = $packageApplication->package_id;
            if (!empty($packageApplication)) {
                $packageApplication->workflow_status = $is_tg > 1 ? 2 : 1;
                $packageApplicationState = $packageApplication->save(false);
            }

            //访问通过，资产包/项目状态改为2
            $pState = true;
            if ($is_tg == 2 && $is_package == 1) {
                $packageStateModel = Package::findOne($package_id);
                $packageStateModel->access = 2;
                $pState = $packageStateModel->save(false);
            }
            if ($is_tg == 2 && $is_package == 2) {
                $projectStateModel = Project::findOne($package_id);
                $projectStateModel->access = 2;
                $pState = $projectStateModel->save(false);
            }
            if ($applicationResultState && $packageApplicationState && $pState) {
                //-------------------访问返回-发送消息----(fly)-----------
                if ($is_package == 1) {
                    $pack_name = (new \yii\db\Query())->from(Package::tableName())->where(['=', 'id', $package_id])->one()['title'];
                } else {
                    $pack_name = (new \yii\db\Query())->from(Project::tableName())->where(['=', 'id', $package_id])->one()['borrower'];
                }
                $application = "访问申请"; //"访问反馈";
                $appStatus = $is_tg == 2 ? 1 : 2;  //审批状态 1 表示审核成功 2表示审核失败
                $approver = \Yii::$app->user->getId(); //审批人
                $applicant_name = (new \yii\db\Query())->from(User::tableName())->where(['=', 'id', $approver])->one()['realname'];
                $applicant_bumen = (new \yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai', 'user.department = ai.name')->where(['=', 'id', $approver])->one()['description'];
                $appSuggest = $noteFW;//审批意见
                $messageArr = [
                    'pack_name' => $pack_name,
                    'application' => $application,
                    'appStatus' => $appStatus,
                    'approver' => $applicant_bumen . '-' . $applicant_name,
                    'appSuggest' => $appSuggest,
                ];
                $appModel = PackageApplication::findOne($application_id);
                if (!empty($appModel)) {
                    $user_id = [$appModel['proposer']];
                } else {
                    $user_id = 0;
                }
                //如果没有审核管理员则不发送数据
                if (!empty($user_id) && is_array($user_id)) {
                    $data = [];
                    $data['sender'] = \Yii::$app->user->getId();//发件人id
                    $data['package_project_id'] = $package_id;//资产包id
                    $data['is_package'] = $is_package;//是否是资产包/1是资产包/2是项目
                    $data['message_val'] = json_encode($messageArr); //消息内容 json

                    $data['user_id'] = $user_id;//收件人id
                    $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
                    //区分是发送消息是 立项/审批
                    $is_fangwen = Yii::$app->request->post('is_fangwen', 1); //1立项 2访问
                    if ($is_fangwen) {
                        $data['message_group'] = \Yii::$app->params['SHENPIN_FANKUI_LX']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/
                    } else {
                        $data['message_group'] = \Yii::$app->params['SHENPIN_FANKUI_FW']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/
                    }

                    $param = [];
                    $param['where_sender'] = \Yii::$app->user->getId();//发件人id
                    $param['where_is_package'] = $is_package;//是否是资产包/1是资产包/2是项目
                    $param['where_package_project_id'] = $package_id;//资产包id
                    if ($is_fangwen) {
                        $param['where_message_group'] = \Yii::$app->params['SHENPIN_FANKUI_LX'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                    } else {
                        $param['where_message_group'] = \Yii::$app->params['SHENPIN_FANKUI_FW'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                    }
                    $messageState = InstationMessage::saveMessage($param, $data);
                } else {
                    $messageState['code'] = 200;
                    $messageState['message'] = '审批成功,无审核管理员,没发送消息';
                }
                if (!empty($messageState) && $messageState['code'] == 200) {
                    //添加访问权限
                    $add_true = false; //默认无添加权限
                    if (!empty($is_package) && $is_package == 1 && $is_tg == 2) {
                        if (!empty($user_id) && is_array($user_id)) {
                            $user_id = $user_id[0];
                            $packageSelect = (new \yii\db\Query())->from('package')->where(['=', 'id', $package_id])->one();
                            $access_user_id = $packageSelect['access_users'] . ',' . $user_id;
                            $packageModel = Package::findOne($package_id);
                            $packageModel->access_users = $access_user_id;
                            $add_true = $packageModel->save(false);
                        }
                    }
                    if (!empty($is_package) && $is_package == 2 && $is_tg == 2) {
                        if (!empty($user_id) && is_array($user_id)) {
                            $user_id = $user_id[0];
                            $projectSelect = (new \yii\db\Query())->from('project')->where(['=', 'id', $package_id])->one();
                            $access_user_id = $projectSelect['access_users'] . ',' . $user_id;
                            $projectModel = Project::findOne($package_id);
                            $projectModel->access_users = $access_user_id;
                            $add_true = $projectModel->save(false);
                        }
                    }
                    if ($add_true) {
                        $transaction->commit();
                        return json_encode(Responses::response200('', 1, '审批成功-发送消息成功-审核权限成功'));
                    }
                    $transaction->commit();
                    return json_encode(Responses::response200('', 1, '审批成功-发送消息成功-审核权限失败'));
                } else {
                    return json_encode(Responses::response400('审批成功-发送消息失败'));
                }
//        //-------------------审核立项-----发送消息------(fly)------
//                //-----fly---审批成功添加权限---start---
//                //$result==2则表示通过审核
//                $is_package = Yii::$app->request->get('is_package',1);   //1资产包 2项目
//                if($is_tg==2){
//                    $user_id = Yii::$app->request->post('user_id', 0);
//                    //资产包权限
//                    $packageOneData = Package::find()->where(['=','id',$package_id])->one();
//                    if (!empty($packageOneData['access_users'])){
//                        $access_users = $packageOneData['access_users'].','.$user_id;
//                    }else{
//                        $access_users = $user_id;
//                    }
//                    //单项目权限
//                    $projectOneData = Project::find()->where(['=','id',$package_id])->one();
//                    if (!empty($projectOneData['access_users'])){
//                        $access_users = $projectOneData['access_users'].','.$user_id;
//                    }else{
//                        $access_users = $user_id;
//                    }
//                    if ($is_package==1){
//                        $packageOneData->access_users = $access_users;
//                        $packageState = $packageOneData->save(false);
//                        $projectOneData->access_users = $access_users;
//                        $projectState = $projectOneData->save(false);
//                        if ($packageState && $projectState){
//                            return json_encode(Responses::response200('', 1, '审批成功-发送消息成功'));
//                        }
//                        return json_encode(Responses::response400('审批成功-设置用户申请权限失败'));
//                    }else{
//                        $packageOneData->access_users = $access_users;
//                        $packageState = $packageOneData->save(false);
//                        if ($packageState){
//                            return json_encode(Responses::response200('', 1, '审批成功-发送消息成功'));
//                        }
//                        return json_encode(Responses::response400('审批成功-设置用户申请权限失败'));
//                    }
//                }
//                //-----fly---审批成功添加权限---end----
                return json_encode(Responses::response200([], 1, "审核成功"));
            }
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return json_encode(Responses::response400('审核失败'));
        }
    }
}
